define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');


    var weixin = {
        buttonList: [],//一级菜单
        subButton: {},//二级菜单
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "微信公众号按钮配置") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });

            this.initWeixin();
            this.initValidator();
            this.bindEvent();
        },

        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#weixin_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    btn_name: {
                        message: '菜单标题输入错误',
                        validators: {
                            stringLength: {
                                message: '请输入1-7位的菜单标题',
                                min: 1,
                                max: 7
                            }
                        }
                    },
                    btn_url: {
                        message: '网页链接输入错误',
                        validators: {
                            uri: {
                                message: '请输入正确的URL'
                            }
                        }
                    }
                }
            });
        },
        //初始化开放城市
        initWeixin: function () {
            var self = this;
            CRM.request({
                "type": 'get',
                "url": CRM.getOuterUrl('/member/getGzhMenu.do'),
                "dataType": "json",
                contentType: "application/json",
                "success": function (req) {
                    if (req.status) {
                        $("#btn_div").html("");
                        $("#weixin_form").hide();
                        self.buttonList = [];
                        self.subButton = {};
                        if (!req.entry.button || req.entry.button.length < 3) {
                            $("#add_new").show();
                        } else {
                            $("#add_new").hide();
                        }
                        $.each(req.entry.button, function (index, item) {
                            item.id = index;
                            self.buttonList.push(item);
                            var btnGroup = $('<div class="btn-group"></div>');
                            var buttonObj = $('<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="javascript:modify(' + index + ')">' + item.name + '</button>');
                            buttonObj.append('<span class="caret"></span>');
                            var ulObj = $('<ul class="dropdown-menu"></ul>');
                            $.each(item.sub_button, function (_index, _item) {
                                if (!self.subButton[index]) {
                                    self.subButton[index] = [];
                                }
                                self.subButton[index].push(_item);
                                ulObj.append($('<li><a href="javascript:modifySub(' + index + ',' + _index + ')">' + _item.name + '</a></li>'));
                            });
                            if (!item.sub_button || item.sub_button.length < 5) {
                                ulObj.append($('<li><a href="javascript:add(' + item.id + ',\'sub_btn\');" class="btn btn-warning">添加子菜单</a></li>'));
                            }
                            btnGroup.append(buttonObj);
                            btnGroup.append(ulObj);
                            $("#btn_div").append(btnGroup);
                        });
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 修改一级菜单
         * @param btnId
         */
        modify: function (btnId) {
            $("#btn_type").val("");
            $("#btn_name").val("");
            $("#btn_key").val("");
            $("#btn_url").val("");
            $("#btn_media_id").val("");
            $("#btn_key_div").hide();
            $("#btn_url_div").hide();
            $("#btn_media_id_div").hide();
            $("#btn_delete").show();
            var btnObj = this.buttonList[btnId];
            if (btnObj) {
                $("#btn_type").val(btnObj.type);
                $("#btn_name").val(btnObj.name);
                if (btnObj.type == "view") {
                    $("#btn_url").val(btnObj.url);
                    $("#btn_url_div").show();
                } else if (btnObj.type == "media_id" || btnObj.type == "view_limited") {
                    $("#btn_media_id").val(btnObj.media_id);
                    $("#btn_media_id_div").show();
                } else if (btnObj.type) {
                    $("#btn_key").val(btnObj.key);
                    $("#btn_key_div").show();
                }
            }
            $("#btn_id_type").val("btn");
            $("#btn_id").val(btnId);
            $("#weixin_form").show();
            $("#weixin_form").data('bootstrapValidator').resetForm();
            this.changeValidator();
        },
        /**
         * 修改二级菜单
         * @param btnId
         * @param subBtnId
         */
        modifySub: function (btnId, subBtnId) {
            $("#btn_type").val("");
            $("#btn_name").val("");
            $("#btn_key").val("");
            $("#btn_url").val("");
            $("#btn_media_id").val("");
            $("#btn_key_div").hide();
            $("#btn_url_div").hide();
            $("#btn_media_id_div").hide();
            $("#btn_delete").show();
            var btnObj = this.subButton[btnId][subBtnId];
            if (btnObj) {
                $("#btn_type").val(btnObj.type);
                $("#btn_name").val(btnObj.name);
                if (btnObj.type == "view") {
                    $("#btn_url").val(btnObj.url);
                    $("#btn_url_div").show();
                } else if (btnObj.type == "media_id" || btnObj.type == "view_limited") {
                    $("#btn_media_id").val(btnObj.media_id);
                    $("#btn_media_id_div").show();
                } else if (btnObj.type) {
                    $("#btn_key").val(btnObj.key);
                    $("#btn_key_div").show();
                }
            }
            $("#btn_id").val(btnId + "_" + subBtnId);
            $("#btn_id_type").val("sub_btn");
            $("#weixin_form").show();
            $("#weixin_form").data('bootstrapValidator').resetForm();
            this.changeValidator();
        },
        /**
         * 新增
         * @param btnId
         * @param idType
         */
        add: function (btnId, idType) {
            $("#btn_type").val("");
            $("#btn_name").val("");
            $("#btn_key").val("");
            $("#btn_url").val("");
            $("#btn_media_id").val("");
            $("#btn_key_div").hide();
            $("#btn_url_div").hide();
            $("#btn_media_id_div").hide();
            $("#btn_delete").hide();
            if (btnId || btnId == 0) {
                $("#btn_id").val(btnId);
            } else {
                $("#btn_id").val("");
            }
            $("#btn_id_type").val(idType);
            $("#weixin_form").show();
            $("#weixin_form").data('bootstrapValidator').resetForm();
            this.changeValidator();
        },
        /**
         * 保存
         */
        save: function () {
            var self = this;
            $("#weixin_form").data('bootstrapValidator').resetForm();
            $("#weixin_form").data('bootstrapValidator').validate();
            if ($("#weixin_form").data('bootstrapValidator').isValid()) {
                var _values = {};
                _values.type = $("#btn_type").val();
                _values.name = $("#btn_name").val();
                if (_values.type == "view") {
                    _values.url = $("#btn_url").val();
                } else if (_values.type == "media_id" || _values.type == "view_limited") {
                    _values.media_id = $("#btn_media_id").val();
                } else {
                    _values.key = $("#btn_key").val();
                }
                if (!_values.type) {
                    _values.type = undefined;
                }
                if (!_values.key) {
                    _values.key = undefined;
                }
                if ("btn" == $("#btn_id_type").val()) {//一级菜单
                    if ($("#btn_id").val()) {//更新操作
                        $.each(self.buttonList, function (index, item) {
                            if (item && item.id == $("#btn_id").val()) {
                                _values.id = item.id;
                                self.buttonList[index] = _values;
                            }
                        });
                    } else {
                        this.buttonList.push(_values);
                    }
                } else if ("sub_btn" == $("#btn_id_type").val()) {
                    var _btnIdValues = $("#btn_id").val();
                    var _btnIdValue = _btnIdValues.split("_");
                    $.each(self.buttonList, function (index, item) {
                        if (item && item.id == _btnIdValue[0]) {
                            if (!self.subButton[item.id]) {
                                self.subButton[item.id] = [];
                            }
                            if (_btnIdValue[1]) {//更新操作
                                self.subButton[_btnIdValue[0]][_btnIdValue[1]] = _values;
                            } else {
                                self.subButton[item.id].push(_values);
                            }


                        }
                    });
                }
                $.each(self.buttonList, function (index, item) {
                    item.sub_button = self.subButton[item.id];
                    item.id = undefined;
                });
                var _data = {
                    "button": self.buttonList
                }
                CRM.request({
                    "type": 'POST',
                    "url": CRM.getOuterUrl('/member/setGzhMenu.do'),
                    "dataType": "json",
                    contentType: "application/json",
                    "data": JSON.stringify(_data),
                    "success": function (req) {
                        if (req.status) {
                            CRM.showDialog("保存成功！");
                        } else {
                            CRM.showDialog(req.message);
                        }
                        self.initWeixin();
                    }
                });

            }
        },
        /**
         *删除菜单
         */
        delBtn: function () {
            if (confirm('确认删除此菜单，本操作无法恢复！')) {
                var self = this;
                if ("btn" == $("#btn_id_type").val()) {//一级菜单
                    $.each(self.buttonList, function (index, item) {
                        if (item && item.id == $("#btn_id").val()) {
                            self.buttonList.splice(index, 1);
                        }
                    });

                }else if ("sub_btn" == $("#btn_id_type").val()) {
                    var _btnIdValues = $("#btn_id").val();
                    var _btnIdValue = _btnIdValues.split("_");
                    self.subButton[_btnIdValue[0]].splice(_btnIdValue[1], 1);
                    if(self.subButton[_btnIdValue[0]].length == 0){
                        self.buttonList[_btnIdValue[0]].type = "click";
                        self.buttonList[_btnIdValue[0]].key = "click";
                    }
                }
                $.each(self.buttonList, function (index, item) {
                    item.sub_button = self.subButton[item.id];
                    item.id = undefined;
                });
                $.each(self.buttonList, function (index, item) {
                    item.id = undefined;
                });
                var _data = {
                    "button": self.buttonList
                }
                CRM.request({
                    "type": 'POST',
                    "url": CRM.getOuterUrl('/member/setGzhMenu.do'),
                    "dataType": "json",
                    contentType: "application/json",
                    "data": JSON.stringify(_data),
                    "success": function (req) {
                        if (req.status) {
                            CRM.showDialog("删除成功！");
                        } else {
                            CRM.showDialog(req.message);
                        }
                        self.initWeixin();
                    }
                });
            }
        },
        /**
         * 菜单类型变化
         */
        btnTypeChange: function () {
            var _type = $("#btn_type").val();
            $("#btn_key_div").hide();
            $("#btn_url_div").hide();
            $("#btn_media_id_div").hide();
            if (_type == "view") {
                $("#btn_url_div").show();
            } else if (_type == "media_id" || _type == "view_limited") {
                $("#btn_media_id_div").show();
            } else if(_type){
                $("#btn_key_div").show();
            }
        },
        /**
         * 验证动态变化
         */
        changeValidator:function(){
            if(($("#btn_id").val() || $("#btn_id").val() == 0) && "btn" == $("#btn_id_type").val()){//一级菜单更新操作
                $("#weixin_form").data('bootstrapValidator').enableFieldValidators("btn_type", false);
            }else{
                $("#weixin_form").data('bootstrapValidator').enableFieldValidators("btn_type", true);
            }
        },
        bindEvent: function () {
            var self = this;
            $("#btn_save").on('click', function () {
                self.save();
            });
            $("#add_new").on('click', function () {
                self.add(null, 'btn');
            });
            $("#btn_delete").on('click', function () {
                self.delBtn();
            });
            $("#btn_type").on('change', function () {
                self.btnTypeChange();
            });

        }
    };

    window.add = $.proxy(weixin.add, weixin);
    window.modify = $.proxy(weixin.modify, weixin);
    window.modifySub = $.proxy(weixin.modifySub, weixin);


    weixin.init();
});